if(!localStorage.getItem('ids')){
	localStorage.setItem('ids', '[]');
}

$(document).ready(function(){
	initGraphics();
	tracker.init();
	//tracker.updateAll();
});

var tracker = {
	parcelIDs: JSON.parse(localStorage.getItem('ids')),
	parcels: {},
	init: function(){
		$.each(localStorage.getItem('ids')?JSON.parse(localStorage.getItem('ids')):[], function(i, id){
			tracker.parcels[id] = new TrackInfo(id);
		});
		
		tracker.updateAll();
		window.setInterval(tracker.updateAll, 5 * 60 * 1000);
	},
	add: function(id, callback){
		var newParcel = new TrackInfo(id);
		newParcel.update(function(trackStatus){
				if($.inArray(id, tracker.parcelIDs) < 0){
					tracker.parcels[id] = newParcel;
					tracker.parcelIDs.push(id);
					localStorage.setItem('ids', JSON.stringify(tracker.parcelIDs));
				}
				callback(id);
		});
	},
	remove: function(id){
		console.log(id);
		tracker.parcelIDs = $.grep(tracker.parcelIDs, function(pid){
			return pid == id;
		}, true);
		localStorage.setItem('ids', JSON.stringify(tracker.parcelIDs));
		delete localStorage[id];
	},
	updateAll: function(){
		$.each(tracker.parcels, function(i, parcel){
			parcel.update(function(trackStatus){
					tracker.notify(parcel.id, trackStatus);
			});
		})
	},
	update: function(id, callback){
		tracker.parcels[id].update(callback);
		
	},
	notify: function(id, trackStatus){
		var notification = webkitNotifications.createNotification(
			'img/drop_box-48.png', 
			id, 
			trackStatus.data.date + ": " + trackStatus.data.status + " " + trackStatus.data.summary
		);
		notification.show();
	}
}

$.fn.reverse = [].reverse;
